package org.mm.proxycache.http;

import static com.google.common.base.Objects.nonNull;

import org.apache.mina.common.IoBuffer;

public class HttpChunk
{
    private final int size;

    private final IoBuffer data;

    private final HttpMessage message;

    public HttpChunk( MutableHttpMessage message, IoBuffer buffer, int dataSize )
    {
        this.message = message;
        message.addChunkSize( dataSize );
        size = dataSize;

        data = IoBuffer.wrap( buffer.array(), buffer.arrayOffset() + buffer.position(), size );
        buffer.skip( size );
    }

    public IoBuffer data()
    {
        return data;
    }

    public int size()
    {
        return size;
    }

    public HttpMessage message()
    {
        return message;
    }

    public boolean isLast()
    {
        return size == 0;
    }

    public static HttpChunk lastChunk( HttpMessage message )
    {
        return new HttpChunk( message );
    }

    private HttpChunk( HttpMessage message )
    {
        size = 0;
        data = null;
        this.message = nonNull( message );
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString()
    {
        return String.format( "HttpChunk(%d)", size );
    }

}
